package ServerClient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ServerThread extends Thread {
	
	private Socket sock;
	private BufferedReader in;
	private PrintWriter out;
	
	public ServerThread(Socket sock){
		this.sock = sock;
		
		try {
			//inicijalizacija ulazno/izlaznog sistema
			in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())),true);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		super.run();
		try {
			//citanje zahteva
			String request = "";

			while(!request.equals("QUIT")){
				request = in.readLine();
				
				if(request.toUpperCase().startsWith("LOGIN ")){
					String user = request.substring(6, request.length());
					
					URL url = new URL("http://localhost:8080/WEBPogramiranje/LogInServlet");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					
					String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(user, "UTF-8");
					data += "&" + URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("CommandPrompt", "UTF-8");
	
					BufferedWriter servletOut = 
							new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
					servletOut.write(data);
					servletOut.flush();
					servletOut.close();
					
					BufferedReader servletIn = 
							new BufferedReader(new InputStreamReader(conn.getInputStream()));
			            	
					String response;
					while ( (response = servletIn.readLine()) != null ) {
						System.out.println( response );
						out.println(response);
					}
					servletIn.close();
			            
				} else if(request.toUpperCase().startsWith("REGISTER ")){	
					String user = request.substring(9, request.length());
					
					URL url = new URL("http://localhost:8080/WEBPogramiranje/RegistrationServlet");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					
					String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(user, "UTF-8");
					data += "&" + URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("CommandPrompt", "UTF-8");
	
					BufferedWriter servletOut = 
							new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
					servletOut.write(data);
					servletOut.flush();
					servletOut.close();
					
					BufferedReader servletIn = 
							new BufferedReader(new InputStreamReader(conn.getInputStream()));
			            	
					String response;
					while ( (response = servletIn.readLine()) != null ) {
						System.out.println( response );
						out.println(response);
					}
					servletIn.close();
				
				} else if(request.toUpperCase().startsWith("ADD ")){
					String data = "";
					String flight = request.substring(4, request.length());
					flight = flight.replaceAll("\t", " ");
					flight = flight.trim();
					
					try{
						String idLeta = flight.substring(0, flight.indexOf(" "));
						flight = flight.substring(flight.indexOf(" ")+1);
						flight = flight.trim();
						
						String datumPolaska = flight.trim().substring(0, flight.indexOf(" "));
						flight = flight.substring(flight.indexOf(" ")+1);
						flight = flight.trim();

						String datumDolaska = flight.trim().substring(0, flight.indexOf(" "));
						flight = flight.substring(flight.indexOf(" ")+1);
						flight = flight.trim();
						
						try {
							Date datumPolaskaDate = new SimpleDateFormat("dd.MM.yyyy_HH:mm").parse(datumPolaska);
							Date datumDolaskaDate = new SimpleDateFormat("dd.MM.yyyy_HH:mm").parse(datumDolaska);
						} catch (ParseException e) {
							out.println("Neispravni datum");
							continue;
						}
						
						String polazniAerodrom = flight.trim().substring(0, flight.indexOf(" "));
						flight = flight.substring(flight.indexOf(" ")+1);
						flight = flight.trim();

						String odrediste = flight.trim().substring(0, flight.indexOf(" "));
						flight = flight.substring(flight.indexOf(" ")+1);
						flight = flight.trim();
						
						String brojPutnika = flight.trim();

						data = URLEncoder.encode("idLeta", "UTF-8") + "=" + URLEncoder.encode(idLeta, "UTF-8");
						data += "&" + URLEncoder.encode("datumPolaska", "UTF-8") + "=" + URLEncoder.encode(datumPolaska, "UTF-8");
						data += "&" + URLEncoder.encode("datumDolaska", "UTF-8") + "=" + URLEncoder.encode(datumDolaska, "UTF-8");
						data += "&" + URLEncoder.encode("polazniAerodrom", "UTF-8") + "=" + URLEncoder.encode(polazniAerodrom, "UTF-8");
						data += "&" + URLEncoder.encode("odrediste", "UTF-8") + "=" + URLEncoder.encode(odrediste, "UTF-8");
						data += "&" + URLEncoder.encode("brojPutnika", "UTF-8") + "=" + URLEncoder.encode(brojPutnika, "UTF-8");
						data += "&" + URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("CommandPrompt", "UTF-8");
						
					
					} catch(StringIndexOutOfBoundsException e){
						out.println("Neispravni podaci");
						continue;
					}
					
					URL url = new URL("http://localhost:8080/WEBPogramiranje/AddFlightServlet");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					
					BufferedWriter servletOut = 
							new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
					servletOut.write(data);
					servletOut.flush();
					servletOut.close();
					
					BufferedReader servletIn = 
							new BufferedReader(new InputStreamReader(conn.getInputStream()));
			            	
					String response;
					while ( (response = servletIn.readLine()) != null ) {
						System.out.println( response );
						out.println(response);
					}
					servletIn.close();

				} else if(request.toUpperCase().startsWith("LIST ")){
					String flightId = request.substring(5, request.length());
					
					URL url = new URL("http://localhost:8080/WEBPogramiranje/listFlightServlet");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					
					String data = URLEncoder.encode("listPassenger", "UTF-8") + "=" + URLEncoder.encode(flightId, "UTF-8");
					data += "&" + URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("CommandPrompt", "UTF-8");
	
					
					BufferedWriter servletOut = 
							new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
					servletOut.write(data);
					servletOut.flush();
					servletOut.close();
					
					BufferedReader servletIn = 
							new BufferedReader(new InputStreamReader(conn.getInputStream()));
			            	
					String response;
					while ((response = servletIn.readLine()) != null) {
						System.out.println( response );
						out.println(response);
					}

					servletIn.close();
					
	
				} else if(request.equalsIgnoreCase("LIST_ALL")){
					URL url = new URL("http://localhost:8080/WEBPogramiranje/listFlightServlet");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					
					String data = URLEncoder.encode("listFlight", "UTF-8") + "=" + URLEncoder.encode("flights", "UTF-8");
					data += "&" + URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("CommandPrompt", "UTF-8");
	
					
					BufferedWriter servletOut = 
							new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
					servletOut.write(data);
					servletOut.flush();
					servletOut.close();
					
					BufferedReader servletIn = 
							new BufferedReader(new InputStreamReader(conn.getInputStream()));
			            	
					String response;
					while ( (response = servletIn.readLine()) != null ) {
						System.out.println( response );
						out.println(response);
					}
					servletIn.close();
				} else if(request.toUpperCase().startsWith("RESERVE ")){
					String reserve = request.substring(8, request.length());
					reserve = reserve.replaceAll("\t", " ");
					reserve = reserve.trim();
					
					String data = "";
					
					try{
						String idLeta = reserve.substring(0, reserve.indexOf(" "));
						reserve = reserve.substring(reserve.indexOf(" ")+1);
						reserve = reserve.trim();
						
						String jmbg = reserve.trim().substring(0, reserve.indexOf(" "));
						reserve = reserve.substring(reserve.indexOf(" ")+1);
						reserve = reserve.trim();

						String ime = reserve.trim().substring(0, reserve.indexOf(" "));
						reserve = reserve.substring(reserve.indexOf(" ")+1);
						reserve = reserve.trim();
						
						String prezime = reserve.trim();
						
						data = URLEncoder.encode("idLeta", "UTF-8") + "=" + URLEncoder.encode(idLeta, "UTF-8");
						data += "&" + URLEncoder.encode("JMBG", "UTF-8") + "=" + URLEncoder.encode(jmbg, "UTF-8");
						data += "&" + URLEncoder.encode("ime", "UTF-8") + "=" + URLEncoder.encode(ime, "UTF-8");
						data += "&" + URLEncoder.encode("prezime", "UTF-8") + "=" + URLEncoder.encode(prezime, "UTF-8");
						data += "&" + URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("CommandPrompt", "UTF-8");
					} catch(StringIndexOutOfBoundsException e){
						out.println("Neispravni podaci");
						continue;
					}
					
					URL url = new URL("http://localhost:8080/WEBPogramiranje/ReservationServlet");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					
					BufferedWriter servletOut = 
							new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
					servletOut.write(data);
					servletOut.flush();
					servletOut.close();
					
					BufferedReader servletIn = 
							new BufferedReader(new InputStreamReader(conn.getInputStream()));
			            	
					String response;
					while ( (response = servletIn.readLine()) != null ) {
						System.out.println( response );
						out.println(response);
					}
					servletIn.close();
					
					
				} else if(request.toUpperCase().startsWith("CANCEL ")){
					String cancel = request.substring(7, request.length());
					cancel = cancel.replaceAll("\t", " ");
					cancel = cancel.trim();
					
					String data = "";
					
					try {
						String idLeta = cancel.trim().substring(0, cancel.indexOf(" "));
						cancel = cancel.substring(cancel.indexOf(" ")+1);
						
						String jmbg = cancel.trim();
						
						data = URLEncoder.encode("idLeta", "UTF-8") + "=" + URLEncoder.encode(idLeta, "UTF-8");
						data += "&" + URLEncoder.encode("JMBG", "UTF-8") + "=" + URLEncoder.encode(jmbg, "UTF-8");
						data += "&" + URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("CommandPrompt", "UTF-8");
					
					} catch(StringIndexOutOfBoundsException e){
						out.println("Neispravni podaci");
						continue;
					}
					
					URL url = new URL("http://localhost:8080/WEBPogramiranje/CancelServlet");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					
					BufferedWriter servletOut = 
							new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
					servletOut.write(data);
					servletOut.flush();
					servletOut.close();
					
					BufferedReader servletIn = 
							new BufferedReader(new InputStreamReader(conn.getInputStream()));
			            	
					String response;
					while ( (response = servletIn.readLine()) != null ) {
						System.out.println( response );
						out.println(response);
					}
					servletIn.close();
					
				} else if (request.toUpperCase().startsWith("LIST_PASSENGER ")){
					String listFlight = request.substring(15, request.length());
					listFlight = listFlight.trim();
					
					
					String data = URLEncoder.encode("listFlight", "UTF-8") + "=" + URLEncoder.encode(listFlight, "UTF-8");
					data += "&" + URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("CommandPrompt", "UTF-8");
					
					URL url = new URL("http://localhost:8080/WEBPogramiranje/listFlightServlet");
					URLConnection conn = url.openConnection();
					conn.setDoOutput(true);
					
					BufferedWriter servletOut = 
							new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
					servletOut.write(data);
					servletOut.flush();
					servletOut.close();
					
					BufferedReader servletIn = 
							new BufferedReader(new InputStreamReader(conn.getInputStream()));
			            	
					String response;
					while ( (response = servletIn.readLine()) != null ) {
						System.out.println( response );
						out.println(response);
					}
					servletIn.close();
					
				} else if(request.equalsIgnoreCase("QUIT")){
					break;
				}
			}
			out.println(request);
			
			in.close();
			out.close();
			sock.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
